package cn.fl.project.transfer.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.condition.SysUsrQueryCondition;
import cmm.user.facade.system.dto.SysOrgDTO;
import cmm.user.facade.system.dto.SysUsrDTO;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.dto.PrjBscInfoDTO;
import cn.fl.project.dto.PrjTransferInfoDTO;
import cn.fl.project.service.IPrjPrdInvoiceService;
import cn.fl.project.service.IProjectApiService;
import cn.fl.project.transfer.service.IPrjTransferInfoService;
import cn.fl.project.transfer.vo.PrjTransferInfoVO;
import cn.fl.project.transform.PrjBscInfoVOTransform;
import cn.fl.project.transform.PrjTransferInfoVOTransform;
import cn.fl.project.vo.PrjBscInfoVO;

/**
 * @Description: 项目移交记录 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class PrjTransferInfoServiceImpl implements IPrjTransferInfoService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(IPrjPrdInvoiceService.class);
	@Autowired
	private IProjectApiService projectApiService;
	@Autowired
	private ISysOrgApiService sysOrgApiService;// 组织机构
	@Autowired
    private ISysUsrApiService sysUsrApiService;
	
	/**
	 * TODO 自定义 API 暴露服务
	 */
	

	
	@Override
	public Long add(PrjTransferInfoVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "add", "新增对象不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		return this.projectApiService.addPrjTransferInfo(PrjTransferInfoVOTransform.toDTO(entity));
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page)page = new Pager();
		page= this.projectApiService.searchPrjTransferInfoListPage(page,CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		page.setResultList(PrjTransferInfoVOTransform.toVOList((List<PrjTransferInfoDTO>) page.getResultList()));
		List<SysOrgDTO> list = this.sysOrgApiService.searchSysOrgListBy(CurrentThreadContext.getCurrentSysCd());
		Map<String, SysOrgDTO> buOrgCdMap = new HashMap<>();
		if (CollectionUtils.isNotEmpty(list)) {
			for (SysOrgDTO sysOrgDTO : list) {
				buOrgCdMap.put(sysOrgDTO.getOrgCd(), sysOrgDTO);
			}
		}
		SysOrgDTO sysOrgDTO = null;
		String orgCd = null;
		List<PrjTransferInfoVO> vos = (List<PrjTransferInfoVO>)page.getResultList();
		if(CollectionUtils.isNotEmpty(vos)){
			for(PrjTransferInfoVO vo :vos){
				if (buOrgCdMap.containsKey(vo.getCstMgrOrgCd())) {//新客户经理省公司
					sysOrgDTO = buOrgCdMap.get(vo.getCstMgrOrgCd());
					orgCd = sysOrgDTO.getOrgCd();
					while(orgCd.length()>8){
					   if("4".equals(sysOrgDTO.getOrgTypCd())){//分公司
							vo.setCyOrgCdNm(sysOrgDTO.getOrgNm());
						}else if("3".equals(sysOrgDTO.getOrgTypCd())){//省公司
							vo.setPrOrgCdNm(sysOrgDTO.getOrgNm());
							 break;
						}
						orgCd = orgCd.substring(0,orgCd.length()-4);
						if(buOrgCdMap.containsKey(orgCd)){
							sysOrgDTO = buOrgCdMap.get(orgCd);
						}else{
							break;
						}
					}
				}
				if (buOrgCdMap.containsKey(vo.getOldCstMgrOrgCd())) {//旧客户经理省公司
					sysOrgDTO = buOrgCdMap.get(vo.getOldCstMgrOrgCd());
					orgCd = sysOrgDTO.getOrgCd();
					while(orgCd.length()>8){
					   if("4".equals(sysOrgDTO.getOrgTypCd())){//分公司
							vo.setOldCyOrgCdNm(sysOrgDTO.getOrgNm());
						}else if("3".equals(sysOrgDTO.getOrgTypCd())) {//省公司
							vo.setOldPrOrgCdNm(sysOrgDTO.getOrgNm());
							 break;
						}
						orgCd = orgCd.substring(0,orgCd.length()-4);
						if(buOrgCdMap.containsKey(orgCd)){
							sysOrgDTO = buOrgCdMap.get(orgCd);
						}else{
							break;
						}
					}
				}
			}
		}
		//设置工号
		this.setBatchCrtUsrNm(vos);
		
		return page;
		
	}
	// 批量设置人员信息
	private void setBatchCrtUsrNm(List<PrjTransferInfoVO> vos) {
		try {
			if (vos != null && vos.size() > 0) {
				List<Long> usrIds = new ArrayList<Long>();// 用户新客户经理ids集合
				List<Long> oldUsrIds = new ArrayList<Long>();// 原客户经理ids集合
				for (PrjTransferInfoVO transferVo : vos) {
					if (StringUtils.isNotEmpty(transferVo.getCstMgrId())) {//新客户经理ID
						if (!usrIds.contains(transferVo.getCstMgrId())) {
							usrIds.add(transferVo.getCstMgrId());
						}
					}
					if (StringUtils.isNotEmpty(transferVo.getOldCstMgrId())) {//原客户经理ID
						if (!oldUsrIds.contains(transferVo.getOldCstMgrId())) {
							oldUsrIds.add(transferVo.getOldCstMgrId());
						}
					}
					//设置事业部
					if (StringUtils.isNotBlank(transferVo.getBuOrgCd())) {
			            String codeNm = this.sysOrgApiService.selectSysOrgNmByOrgCd(transferVo.getBuOrgCd(), CurrentThreadContext.getCurrentSysCd());
			            transferVo.setBuOrgCdNm(codeNm);
			        }
					
				}
				if (usrIds.size() > 0) {
					SysUsrQueryCondition qc = new SysUsrQueryCondition();
					qc.setUsrIdList(usrIds);
					qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
					List<SysUsrDTO> sysUsrDTOList = sysUsrApiService.selectUserList(qc);
					if (sysUsrDTOList != null && sysUsrDTOList.size() > 0) {
						for (PrjTransferInfoVO tVo : vos) {
							for (SysUsrDTO sysUsrDTO : sysUsrDTOList) {
								if (StringUtils.isNotEmpty(tVo.getCstMgrId())
										&& (tVo.getCstMgrId().equals(sysUsrDTO.getId()))) {
									tVo.setCstMgrCd(sysUsrDTO.getUsrNm());
									break;
								}
							}
						}
					}
				}
				if (oldUsrIds.size() > 0) {
					SysUsrQueryCondition qc = new SysUsrQueryCondition();
					qc.setUsrIdList(oldUsrIds);
					qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
					List<SysUsrDTO> sysUsrDTOList = sysUsrApiService.selectUserList(qc);
					if (sysUsrDTOList != null && sysUsrDTOList.size() > 0) {
						for (PrjTransferInfoVO tVo : vos) {
							for (SysUsrDTO sysUsrDTO : sysUsrDTOList) {
								if (StringUtils.isNotEmpty(tVo.getOldCstMgrId())
										&& (tVo.getOldCstMgrId().equals(sysUsrDTO.getId()))) {
									tVo.setOldCstMgrCd(sysUsrDTO.getUsrNm());
									break;
								}
							}
						}
					}
				}
			}
		} catch (Exception e) {
			BaseLogUtils.error(logger, "", "查询人员信息异常:" + e.getMessage());
			e.printStackTrace();
		}
	}
	
	
	
}
